package com.mouchel.gwt.xpath.client;

import java.util.List;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.Window;
import com.google.gwt.xml.client.Attr;
import com.google.gwt.xml.client.DOMException;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.XMLParser;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class GWTXPath implements EntryPoint
{
	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad()
	{
		String url = "/testxml.xml";
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
		
		try
		{
			builder.sendRequest(null, new RequestCallback()
			{				
				@Override
				public void onResponseReceived(Request request, Response response)
				{
					// TODO Auto-generated method stub
					processResponse(response);
				}
				
				@Override
				public void onError(Request request, Throwable exception)
				{
					// TODO Auto-generated method stub
					
				}
			});
		}
		catch (RequestException e)
		{
			e.printStackTrace();
		}
	}
	
	protected void processResponse(Response response)
	{
		try
		{
			Document document = XMLParser.parse(response.getText());
			//Window.alert(document.toString());
			
			//List<Node> results = XPath.evaluate(document.getDocumentElement(), "//value");
			//List<Attr> results = XPath.evaluate(document.getDocumentElemen(), "//item/@index", Attr.class);
			
			Attr att = XPath.evaluateSingle(document, "//bob/@name", Attr.class);
			
			//Window.alert("Found : " + results.size() + " " + results.get(0).getValue());
			Window.alert(att.getValue());
		}
		catch (DOMException e)
		{
			e.printStackTrace();
		}
	}
}